#include"singlelist.h"

void SLNprint(SLN* slnp)
{
	while (slnp)
	{
		printf("%d->", slnp->date);
		slnp = slnp->next;
	}
	printf("NULL\n");
}

SLN* BuyNewNode(SLNtype x)
{
	SLN* newnode = (SLN*)malloc(sizeof(SLN));
	if (newnode == NULL)
	{
		perror("mallodc");
		return NULL;
	}
	newnode->date = x;
	newnode->next = NULL;
	return newnode;
}

void SLNPushBack(SLN** slnpp , SLNtype x)
{
	assert(slnpp);
	SLN* newnode = BuyNewNode(x);
	
	if (*slnpp == NULL)
	{
		*slnpp = newnode;
	}
	else
	{
		SLN* tail = *slnpp;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLNPopBack(SLN** slnpp)
{
	assert(slnpp);
	assert(*slnpp);
	if ((*slnpp)->next == NULL)
	{
		free(*slnpp);
		*slnpp = NULL;
	}
	else
	{
		SLN* tail = *slnpp;
		while (tail->next->next != NULL)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}

void SLNPushFront(SLN** slnpp, SLNtype x)
{
	assert(slnpp);
	SLN* newnode = BuyNewNode(x);
	if (*slnpp == NULL)
	{
		*slnpp = newnode;
	}
	else
	{
		newnode->next = *slnpp;
		*slnpp = newnode;
	}
}

void SLNPopFront(SLN** slnpp)
{
	assert(slnpp);
	assert(*slnpp);
	if ((*slnpp)->next == NULL)
	{
		free(*slnpp);
		*slnpp = NULL;
	}
	else
	{
		SLN* first = *slnpp;
		*slnpp = first->next;
		free(first);
		first = NULL;
	}
}

SLN* SLNFind(SLN* slnp,SLNtype x)
{
	if(slnp==NULL)return NULL;
	SLN* cur = slnp;
	while (cur != NULL)
	{
		if (cur->date == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}
	return NULL;
}

void SLNInsertAfter(SLN* pos,SLNtype x)
{
	assert(pos);
	SLN* newnode = BuyNewNode(x);
	if(pos->next==NULL)
	{
		pos->next = newnode;
	}
	else
	{
	newnode->next = pos->next;
	pos->next = newnode;
	}
}

void SLNEraseAfter(SLN* pos)
{
	assert(pos);
	assert(pos->next);
	if(pos->next==NULL)
	{
		free(pos->next);
		pos->next = NULL;
	}
	else
	{
	SLN* after = pos->next;
	pos->next = pos->next->next;
	free(after);
	after = NULL;
	}
}